package com.qf.controller;

import com.aliyun.oss.OSS;
import com.aliyun.oss.model.ObjectMetadata;
import com.qf.common.ResultEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileInputStream;
import java.io.IOException;
import java.net.URL;
import java.util.Calendar;

@RequestMapping("/file")
@Controller
public class FileController {

    @Autowired
    private OSS ossClinet;

    @Value("${oss.bucketName}")
    private String bucketName;

    private String serverPath = "https://2101-oss.oss-cn-beijing.aliyuncs.com/";

    @RequestMapping("/uploadFile")
    @ResponseBody
    public ResultEntity<String> uploadFile(MultipartFile file) throws IOException {

        // 1、获取文件每次
        String originalFilename = file.getOriginalFilename();

        // 2、设置文件的类型
        ObjectMetadata objectMetadata = new ObjectMetadata();
        if (originalFilename.endsWith("png")) {
            objectMetadata.setContentType("image/png"); // png,jpg,
        } else if (originalFilename.endsWith("jpg")) {
            objectMetadata.setContentType("image/jpeg"); // png,jpg,
        }

        // 3.设置文件上传的路径
        String path = "demo/" + originalFilename;

        // 4.上传文件
        ossClinet.putObject(bucketName, path, file.getInputStream(), objectMetadata);

        // 5.设置过期时间
//        Calendar calendar = Calendar.getInstance();
//        calendar.add(Calendar.HOUR, 3); // 超时时间是30s

        // 6、获取图片的访问地址
       // String url = ossClinet.generatePresignedUrl(bucketName, path, calendar.getTime()).toString();


        return ResultEntity.success(serverPath+path);
    }
}
